﻿@inject IPopupService PopupService

<MButton OnClick="ShowBasic">Basic Prompt</MButton>

<MDivider Class="my-4" />

<MCheckbox @bind-Value="throwException" Label="Throw exception"></MCheckbox>
<MButton OnClick="ShowAsync">Async Prompt</MButton>

<MDivider Class="my-4" />

<MButton OnClick="ShowCustom">Custom Prompt</MButton>

@code {

    private bool throwException;
    private readonly string checkInput = "identity";

    private async Task ShowBasic()
    {
        var confirmed = await PopupService.PromptAsync(
            "Title",
            $"Enter \"{checkInput}\" in the input box below to confirm the operation"
            );

        await HandlePromptResult(confirmed);
    }

    private async Task ShowAsync()
    {
        await PopupService.PromptAsync(
            "Title",
            $"Enter \"{checkInput}\" in the input box below to confirm the operation",
            async args =>
            {
                try
                {
                    if (args.Value == checkInput)
                    {
                        await PopupService.EnqueueSnackbarAsync($"Input('{args.Value}') is equal to '{checkInput}'", AlertTypes.Info);
                        
                        await Task.Delay(1000);

                        if (throwException)
                        {
                            throw new Exception("something wrong!");
                        }
                    }
                    else
                    {
                        await PopupService.EnqueueSnackbarAsync($"Input('{args.Value}') is no equal to '{checkInput}'", AlertTypes.Error);
                        args.Cancel();
                    }
                }
                catch (Exception e)
                {
                    args.Cancel();

                    await PopupService.EnqueueSnackbarAsync(e, true);
                }
            });
    }

    private async Task ShowCustom()
    {
        var input = await PopupService.PromptAsync(param =>
        {
            param.Title = "Title";
            param.Content = $"Enter \"{checkInput}\" in the input box below to confirm the operation";
            param.OkText = "Confirm";
            param.CancelText = "Ignore";
        });

        await HandlePromptResult(input);
    }

    private async Task HandlePromptResult(string input)
    {
        if (input is null)
        {
            await PopupService.EnqueueSnackbarAsync("Cancel was clicked", AlertTypes.Warning);
        }
        else if (input == checkInput)
        {
            await PopupService.EnqueueSnackbarAsync($"Input('{input}') is equal to '{checkInput}'", AlertTypes.Info);
        }
        else
        {
            await PopupService.EnqueueSnackbarAsync($"Input('{input}') is no equal to '{checkInput}'", AlertTypes.Error);
        }
    }

}